/**
 * 
 */
package com.hm.uums.provider;

import java.util.Map;

import org.apache.ibatis.jdbc.SQL;

import com.hm.common.utils.StringUtils;

/**
 * @author hwg
 *
 *         2020年12月30日
 */
public class LogProvider {
	public String count(Map<String, Object> params) {
		SQL sql = new SQL();
		sql.SELECT("count(u.`id`)");
		sql.FROM("module_uums_user as u, `module_gateway_log` as log");
		sql.WHERE("u.`id` = log.`user_id` ");

		if (StringUtils.isNotEmpty(params.get("username"))) {
			sql.WHERE("u.`username` like concat('%',#{username},'%')");
		}
		if (StringUtils.isNotEmpty(params.get("fullname"))) {
			sql.WHERE("u.`full_name` like concat('%',#{fullname},'%')");
		}
		if (StringUtils.isNotEmpty(params.get("reqUrl"))) {
			sql.WHERE("log.`req_url` like concat('%',#{reqUrl},'%')");
		}
		if (StringUtils.isNotEmpty(params.get("clientIp"))) {
			sql.WHERE("log.`client_ip` like concat('%',#{clientIp},'%')");
		}
		return sql.toString();
	}

	public String list(Map<String, Object> params) {
		SQL sql = new SQL();
		sql.SELECT("log.`user_id` as userId");
		sql.SELECT("log.`req_url` as reqUrl");
		sql.SELECT("log.`req_time` as reqTime");
		sql.SELECT("log.`method`");
		sql.SELECT("log.`client_ip` as clientIp");
		sql.SELECT("log.`client_name` as clientName");
		sql.SELECT("log.`status_code` as statusCode");
		sql.SELECT("log.`resp_time` as respTime");
		sql.SELECT("log.`resp_duration` as respDuration");
		sql.SELECT("log.`function_module` as functionModule");
		sql.SELECT("log.`function_code` as functionCode");
		sql.SELECT("log.`function_desc` as functionDesc");
		sql.FROM("`module_gateway_log` as log");
		
		if (StringUtils.isNotEmpty(params.get("userId"))) {
			sql.WHERE("log.`user_id` = #{userId}");
		}

		if (StringUtils.isNotEmpty(params.get("clientIp"))) {
			sql.WHERE("log.`client_ip` = #{clientIp}");
		}
		
		if (StringUtils.isNotEmpty(params.get("reqStartDate"))) {
			sql.WHERE("log.`req_time` >= #{reqStartDate}");
		}
		
		if (StringUtils.isNotEmpty(params.get("reqEndDate"))) {
			sql.WHERE("log.`req_time` <= #{reqEndDate}");
		}
		
		String sortField = StringUtils.toString(params.get("sortField"));
		String sortType = StringUtils.toString(params.get("sortType"));
		if (StringUtils.isNotEmpty(sortField) && StringUtils.isNotEmpty(sortType)) {
			sql.ORDER_BY("${sortField} ${sortType}");
		}

 		sql.LIMIT("#{offset}, #{pageSize}");
		
		String outSql = "select u.`id` as userId, u.`username` as username, u.`full_name` as fullname, log.* from ";
		outSql +="("+sql.toString()+") as log left join `module_uums_user` as u on u.`id` = log.`userId` ";
		
		//二次排序
		if (StringUtils.isNotEmpty(sortField) && StringUtils.isNotEmpty(sortType)) {
			outSql += "order by ${sortField} ${sortType}";
		}
		return outSql;
	}

}
